package com.yizisu.playerlibrary.view.video_view.view

import android.content.Context
import android.util.AttributeSet
import android.view.TextureView
import com.yizisu.playerlibrary.IYzsPlayer
import com.yizisu.playerlibrary.view.video_view.helper.IPlayerConfig
import com.yizisu.playerlibrary.view.video_view.helper.IPlayerHelper

/**
 * 承载画面的view
 * 支持根据尺寸自动布局
 */
open class PlayerTextureView : PlayerRatioLayout, IPlayerHelper {
    private val textureView by lazy {
        TextureView(context).apply {
            addView(this)
        }
    }

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    override fun onAttachPlayerConfig(playerConfig: IPlayerConfig) {
        playerConfig.player?.attachView(textureView)
    }

    override fun onDetachedPlayerConfig(playerConfig: IPlayerConfig) {
        playerConfig.player?.attachView(null)
    }

    override fun isNeedPlayerListener(): Boolean {
        return true
    }

    override fun onVideoSizeChange(
        width: Int,
        height: Int,
        unappliedRotationDegrees: Int,
        pixelWidthHeightRatio: Float,
        playerModel: IYzsPlayer.Model?
    ) {
        super.onVideoSizeChange(
            width,
            height,
            unappliedRotationDegrees,
            pixelWidthHeightRatio,
            playerModel
        )
        setChildRatio(width.toFloat() / height)
    }

    override fun onPlay(playStatus: Boolean, playerModel: IYzsPlayer.Model?) {
        super.onPlay(playStatus, playerModel)
        keepScreenOn = playStatus
    }

    override fun onPause(playStatus: Boolean, playerModel: IYzsPlayer.Model?) {
        super.onPause(playStatus, playerModel)
        keepScreenOn = playStatus
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        keepScreenOn = false
    }
}